package com.ytktt.study.week11.task8;

import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO
 *
 * @author ytk
 */
public class Application {

    private static final String DECR_STOCK_SCRIPT = "if tonumber(redis.call('get', KEYS[1])) > 0 then return redis.call('decr', KEYS[1]) else return 0 end";

    public static void main(String[] args) throws InterruptedException {
        RedisClient redisClient = RedisClient.create("redis://localhost:6379/0");

        ExecutorService executorService = Executors.newFixedThreadPool(6);
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            executorService.submit(() -> {
                int count = 0;
                while (count < 5) {
                    StatefulRedisConnection<String, String> connection = redisClient.connect();
                    RedisCommands<String, String> syncCommands = connection.sync();
                    Long result = syncCommands.eval(DECR_STOCK_SCRIPT, ScriptOutputType.INTEGER, "stock");
                    System.out.println(Thread.currentThread().getName() + "decr: " + result);
                    connection.close();
                    count++;
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();

        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> syncCommands = connection.sync();
        System.out.println("now stock: " + syncCommands.get("stock"));

        connection.close();
        redisClient.shutdown();
    }
}
